import OpenAI from "openai";
import type { Task } from "@/types/task";
import type { MessageType } from "@/types/message";

export const ai = new OpenAI({
  baseURL: "https://ai.gitee.com/v1",
  apiKey: import.meta.env.VITE_GITEE_AI_KEY,
  dangerouslyAllowBrowser: true,
});

const tools = [
  {
    type: "function" as const,
    function: {
      name: "createTask",
      description: "创建一个新任务",
      parameters: {
        type: "object",
        properties: {
          title: {
            type: "string",
            description: "任务标题",
          },
          description: {
            type: "string",
            description: "任务描述",
          },
          type: {
            type: "string",
            enum: ["feature", "task", "bug"],
            description: "任务类型",
          },
          status: {
            type: "string",
            enum: ["todo", "doing", "done"],
            description: "任务状态",
          },
        },
        required: ["title", "type"],
      },
    },
  },
  {
    type: "function" as const,
    function: {
      name: "updateTask",
      description: "更新一个已存在的任务",
      parameters: {
        type: "object",
        properties: {
          taskId: {
            type: "string",
            description: "要更新的任务ID",
          },
          title: {
            type: "string",
            description: "任务标题",
          },
          description: {
            type: "string",
            description: "任务描述",
          },
          type: {
            type: "string",
            enum: ["feature", "task", "bug"],
            description: "任务类型",
          },
          status: {
            type: "string",
            enum: ["todo", "doing", "done"],
            description: "任务状态",
          },
        },
        required: ["taskId"],
      },
    },
  },
  {
    type: "function" as const,
    function: {
      name: "deleteTask",
      description: "删除一个任务",
      parameters: {
        type: "object",
        properties: {
          taskId: {
            type: "string",
            description: "要删除的任务ID",
          },
        },
        required: ["taskId"],
      },
    },
  },
];

export interface TaskFunctions {
  createTask: (task: Partial<Task>) => Promise<void>;
  updateTask: (taskId: string, updates: Partial<Task>) => Promise<void>;
  deleteTask: (taskId: string) => Promise<void>;
}

export type ChatResponse = {
  content: string;
  type: MessageType;
};

export async function* streamChat(
  content: string,
  tasks: Task[],
  taskFunctions: TaskFunctions
): AsyncGenerator<ChatResponse> {
  try {
    const response = await ai.chat.completions.create({
      model: "Qwen2.5-72B-Instruct",
      stream: true,
      messages: [
        {
          role: "system",
          content: `你是一个任务管理助手。当前任务列表：
${tasks
  .map((task) => `- [${task.id}] ${task.title} (${task.type}, ${task.status})`)
  .join("\n")}`,
        },
        {
          role: "user",
          content,
        },
      ],
      tools,
      tool_choice: "auto",
    });

    let toolCall: { name?: string; arguments: string } = { arguments: "" };
    let hasShownCollecting = false;

    for await (const chunk of response) {
      if (chunk.choices[0]?.delta?.tool_calls?.[0]) {
        if (!hasShownCollecting) {
          yield {
            content: "正在收集任务操作...",
            type: "collecting_function",
          };
          hasShownCollecting = true;
        }
        const call = chunk.choices[0].delta.tool_calls[0];
        if (call.function?.name) {
          toolCall.name = call.function.name;
        }
        if (call.function?.arguments) {
          toolCall.arguments += call.function.arguments;
        }
      } else if (chunk.choices[0]?.delta?.content) {
        yield { content: chunk.choices[0].delta.content, type: "text" };
      }
    }

    if (toolCall.name && toolCall.arguments) {
      try {
        yield { content: "正在执行任务操作...", type: "loading" };
        const args = JSON.parse(toolCall.arguments);
        switch (toolCall.name) {
          case "createTask":
            await taskFunctions.createTask(args);
            yield {
              content: "\r✅ 已创建任务",
              type: "success",
            };
            break;
          case "updateTask":
            const { taskId, ...updates } = args;
            await taskFunctions.updateTask(taskId, updates);
            yield { content: "\r✅ 已更新任务", type: "success" };
            break;
          case "deleteTask":
            await taskFunctions.deleteTask(args.taskId);
            yield { content: "\r✅ 已删除任务", type: "success" };
            break;
        }
      } catch (error) {
        console.error("Function call error:", error);
        yield { content: "\r❌ 任务操作失败", type: "error" };
      }
    }
  } catch (error) {
    console.error("AI Chat Error:", error);
    yield { content: "抱歉，AI 响应出错了", type: "error" };
  }
}
